package org.example.spi;

import cn.hutool.core.io.resource.ResourceUtil;
import lombok.extern.slf4j.Slf4j;
import org.example.serialize.Serializer;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author Jiangxiaonan
 * @Description SPI 加载器，支持键值对映射
 * @Date 2024/9/7 17:11
 **/
@Slf4j
public class SpiLoader {

    // 存储已加载的类
    private static Map<String,Map<String, Class<?>>> loaderMap = new ConcurrentHashMap<>();

    // 对象实例缓存，避免重复创建对象
    private static Map<String, Object> instanceCache = new ConcurrentHashMap<>();

    // 系统SPI目录
    private static final String RPC_SYSTEM_SPI_DIR = "META-INF/rpc/system/";

    // 用户自定义SPI目录
    private static final String RPC_CUSTOM_SPI_DIR = "META-INF/rpc/custom/";

    // 扫描路径
    private static final String[] SCAN_DIRS = {RPC_SYSTEM_SPI_DIR, RPC_CUSTOM_SPI_DIR};

    // 动态加载的类列表
    private static final List<Class<?>> LOAD_CLASS_LIST = Arrays.asList(Serializer.class);

    // 加载所有类型
    public static void loadAll() {
        log.info("加载所有SPI");
        for (Class<?> clazz : LOAD_CLASS_LIST) {
            load(clazz);
        }
    }

    // 获取某个接口的实例
    public static <T> T getInstance(Class<T> clazz, String key) {
        String className = clazz.getName();
        Map<String, Class<?>> keyClassMap = loaderMap.get(className);
        if(keyClassMap == null) {
            throw new RuntimeException(String.format("SpiLoader未加载%s类型", className));
        }
        if(!keyClassMap.containsKey(key)) {
            throw new RuntimeException(String.format("SpiLoader的%s不存在key=%的类型", className, key));
        }
        // 获取要加载的实现类类型
        Class<?> implClass = keyClassMap.get(key);
        if(!instanceCache.containsKey(implClass.getName())) {
            try {
                instanceCache.put(implClass.getName(), implClass.newInstance());
            } catch(Exception e) {
                String errorMsg = String.format("SpiLoader创建%s实例失败", implClass.getName());
                throw new RuntimeException(errorMsg, e);
            }
        }
        return (T) instanceCache.get(implClass.getName());
    }

    //加载某个类型
    public static Map<String, Class<?>> load(Class<?> loaderClass) {
        log.info("加载SPI类型：{}", loaderClass.getName());
        // 扫描路径，用户自定义的SPI优先级高于系统SPI
        HashMap<String, Class<?>> keyClassMap = new HashMap<String, Class<?>>();
        for (String scanDir : SCAN_DIRS) {
            List<URL> resources = ResourceUtil.getResources(scanDir + loaderClass.getName());
            for (URL resource : resources) {
                try {
                    InputStreamReader inputStreamReader = new InputStreamReader(resource.openStream(), "UTF-8");
                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                    String line = null;
                    while ((line = bufferedReader.readLine())!= null) {
                        String[] strArray = line.split("=");
                        if (strArray.length > 1) {
                            String key = strArray[0].trim();
                            String className = strArray[1].trim();
                            keyClassMap.put(key, Class.forName(className));
                        }
                    }
                } catch(Exception e) {
                    log.error("加载SPI失败：{}", e.getMessage());
                }
            }
        }
        loaderMap.put(loaderClass.getName(), keyClassMap);
        return keyClassMap;
    }

}
